package com.sws.customer.service.impl;

import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import com.sws.common.exception.ServiceException;
import com.sws.common.utils.DateUtils;
import com.sws.common.utils.PidGeneratorUtil;

import com.sws.common.utils.SecurityUtils;
import com.sws.device.domain.DevDevice;
import com.sws.device.service.IDevDeviceService;
import com.sws.person.ball.CameraServerProperties;
import com.sws.person.domain.PerPerson;
import com.sws.person.service.IPerPersonService;
import com.sws.rel.domain.PersonDeviceRel;
import com.sws.rel.service.IPersonDeviceRelService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.sws.customer.mapper.RyCustomerMapper;
import com.sws.customer.domain.RyCustomer;
import com.sws.customer.service.IRyCustomerService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 核心人员信息Service业务层处理
 * 
 * @author cx
 * @date 2025-06-23
 */
@Service
@Slf4j
public class RyCustomerServiceImpl implements IRyCustomerService 
{
    @Autowired
    private RyCustomerMapper ryCustomerMapper;

    // 注入摄像头人员服务
    @Autowired
    private IPerPersonService perPersonService;

    // 注入人员设备关系服务
    @Autowired
    private IPersonDeviceRelService personDeviceRelService;
    
    // 注入设备服务
    @Autowired
    private IDevDeviceService devDeviceService;
    
    // 注入摄像头服务器配置
    @Autowired
    private CameraServerProperties cameraServerProperties;

    /**
     * 查询核心人员信息
     * 
     * @param id 核心人员信息主键
     * @return 核心人员信息
     */
    @Override
    public RyCustomer selectRyCustomerById(Long id)
    {
        RyCustomer customer = ryCustomerMapper.selectRyCustomerById(id);
        if (customer != null && customer.getFacePhoto() != null) {
            // 动态添加URL前缀
            customer.setFacePhoto(convertToFullUrl(customer.getFacePhoto()));
        }
        return customer;
    }

    /**
     * 查询核心人员信息列表
     * 
     * @param ryCustomer 核心人员信息
     * @return 核心人员信息
     */
    @Override
    public List<RyCustomer> selectRyCustomerList(RyCustomer ryCustomer)
    {
        List<RyCustomer> list = ryCustomerMapper.selectRyCustomerList(ryCustomer);
        // 为每条记录动态添加前缀
        list.forEach(c -> {
            if (c.getFacePhoto() != null) {
                c.setFacePhoto(convertToFullUrl(c.getFacePhoto()));
            }
        });
        return list;
    }

    /**
     * 新增核心人员信息
     * 
     * @param ryCustomer 核心人员信息
     * @return 结果
     */
    @Override
    @Transactional
    public int insertRyCustomer(RyCustomer ryCustomer) {
        // 检查设备ID列表是否提供
        if (ryCustomer.getDeviceIds() == null || ryCustomer.getDeviceIds().isEmpty()) {
            throw new ServiceException("请至少选择一个设备");
        }
        
        // 生成随机PID并设置给客户
        if (ryCustomer.getPid() == null || ryCustomer.getPid().isEmpty()) {
            String randomPid = PidGeneratorUtil.generatePid();
            ryCustomer.setPid(randomPid);
        }

        // 1. 同步到摄像头人员库
        PerPerson perPerson = convertToPerPerson(ryCustomer);
        try {
            // 使用多设备添加方法
            perPerson.setDeviceIds(ryCustomer.getDeviceIds());
            PerPerson addedPerson = perPersonService.addPersontoCamera(perPerson);
            
            // 确保使用相同的PID
            ryCustomer.setPid(addedPerson.getPid());
            perPerson.setPid(addedPerson.getPid());
            
            // 设置照片路径 - 这里保存原始路径，不添加URL前缀
            if (addedPerson.getPhoto() != null) {
                // 确保照片路径中包含设备SN
                String deviceSn = ryCustomer.getDeviceIds().get(0);
                ryCustomer.setFacePhoto(addDeviceSnToPhotoPath(addedPerson.getPhoto(), deviceSn));
            }
        } catch (Exception e) {
            throw new ServiceException("同步到摄像头失败: " + e.getMessage());
        }

        // 2. 保存到客户库
        ryCustomer.setCreateTime(DateUtils.getNowDate());
        int customerResult = ryCustomerMapper.insertRyCustomer(ryCustomer);

        // 3. 创建人员-设备关系记录(已由perPersonService.addPersontoCamera处理)
        
        // 4. 同步添加到人员管理表
        if (customerResult > 0) {
            try {
                // 检查是否已经存在同PID的人员记录
                PerPerson existingPerson = perPersonService.selectPerPersonByPid(ryCustomer.getPid());
                
                if (existingPerson == null) {
                    // 不存在则创建新人员记录
                    perPerson = convertToPerPerson(ryCustomer);
            perPerson.setCreateBy(SecurityUtils.getUsername());
            perPerson.setCreateTime(new Date());
            perPerson.setDelFlag(0);
                    
                    // 将客户的照片路径直接复制到人员表中
                    perPerson.setPhoto(ryCustomer.getFacePhoto());
                    
                    // 设置部门为客户类型
                    String department = "客户";
                    if (ryCustomer.getVipLevel() != null) {
                        switch (ryCustomer.getVipLevel()) {
                            case 1:
                                department = "普通客户";
                                break;
                            case 2:
                                department = "VIP客户";
                                break;
                            case 3:
                                department = "VVIP客户";
                                break;
                            default:
                                department = "客户";
                        }
                    }
                    perPerson.setDepartment(department);
                    
                    log.info("同步添加客户到人员表, PID: {}", ryCustomer.getPid());
            perPersonService.insertPerPerson(perPerson);
                } else {
                    log.info("人员表中已存在相同PID的记录，跳过同步添加: {}", ryCustomer.getPid());
                }
            } catch (Exception e) {
                log.error("同步添加客户到人员表失败: {}", e.getMessage());
                // 不影响主流程，只记录日志
            }
        }

        return customerResult;
    }

    /**
     * 修改核心人员信息
     * 
     * @param ryCustomer 核心人员信息
     * @return 结果
     */
    @Override
    @Transactional
    public int updateRyCustomer(RyCustomer ryCustomer) {
        // 检查设备ID列表是否提供
        if (ryCustomer.getDeviceIds() == null || ryCustomer.getDeviceIds().isEmpty()) {
            throw new ServiceException("请至少选择一个设备");
        }
        
        // 1. 查询原始客户记录（获取原始PID）
        RyCustomer original = ryCustomerMapper.selectRyCustomerById(ryCustomer.getId());
        if (original == null) {
            throw new ServiceException("客户不存在");
        }

        // 2. 处理图片路径 - 检查是否为本地路径
        boolean needUploadPhoto = false;
        String originalPhotoPath = null;
        
        if (ryCustomer.getFacePhoto() != null && 
            !ryCustomer.getFacePhoto().equals(original.getFacePhoto()) && 
            (ryCustomer.getFacePhoto().startsWith("/profile/") || 
             ryCustomer.getFacePhoto().startsWith("profile/"))) {
            // 检测到本地新上传的图片路径，标记需要上传到设备
            needUploadPhoto = true;
            originalPhotoPath = ryCustomer.getFacePhoto();
            log.info("检测到本地图片路径，需要上传到设备: {}", originalPhotoPath);
        }

        // 3. 同步更新到摄像头
        PerPerson perPerson = convertToPerPerson(ryCustomer);
        perPerson.setPid(original.getPid()); // 使用原始PID
        perPerson.setDeviceIds(ryCustomer.getDeviceIds()); // 设置设备ID列表
        
        try {
            // 先检查数据库中是否存在对应的人员记录
            PerPerson existingPerson = perPersonService.selectPerPersonByPid(original.getPid());
            
            if (existingPerson == null) {
                // 如果人员不存在，则创建新人员
                log.info("人员记录不存在，正在创建新人员记录，PID: {}", original.getPid());
                
                if (needUploadPhoto) {
                    // 使用perPersonService上传图片到设备
                    perPerson.setPhoto(originalPhotoPath);
                    PerPerson addedPerson = perPersonService.addPersontoCamera(perPerson);
                    
                    // 使用设备返回的云端图片路径
                    if (addedPerson != null && addedPerson.getPhoto() != null) {
                        // 确保照片路径中包含设备SN
                        String deviceSn = ryCustomer.getDeviceIds().get(0);
                        ryCustomer.setFacePhoto(addDeviceSnToPhotoPath(addedPerson.getPhoto(), deviceSn));
                        log.info("图片已上传到设备，使用设备返回的路径: {}", ryCustomer.getFacePhoto());
                    }
                } else {
                    perPerson.setPhoto(ryCustomer.getFacePhoto()); // 使用原始照片
                    PerPerson addedPerson = perPersonService.addPersontoCamera(perPerson);
                    
                    if (addedPerson != null && addedPerson.getPhoto() != null) {
                        // 确保照片路径中包含设备SN
                        String deviceSn = ryCustomer.getDeviceIds().get(0);
                        ryCustomer.setFacePhoto(addDeviceSnToPhotoPath(addedPerson.getPhoto(), deviceSn));
                    }
                }
            } else {
                // 存在人员记录，更新人员信息
                perPerson.setId(existingPerson.getId());
                
                if (needUploadPhoto) {
                    // 如果是本地新上传的图片，需要更新到设备
                    // 复用perPersonService中更新照片的逻辑
                    perPerson.setPhoto(originalPhotoPath);
                    perPersonService.updatePerPerson(perPerson);
                    
                    // 重新查询以获取设备返回的照片路径
                    PerPerson updatedPerson = perPersonService.selectPerPersonById(existingPerson.getId());
                    if (updatedPerson != null && updatedPerson.getPhoto() != null) {
                        ryCustomer.setFacePhoto(updatedPerson.getPhoto());
                        log.info("图片已更新到设备，使用设备返回的路径: {}", ryCustomer.getFacePhoto());
                    }
                } else {
                    // 如果没有修改照片或者使用的是已有的设备路径
                    if (perPerson.getPhoto() == null && existingPerson.getPhoto() != null) {
                        perPerson.setPhoto(existingPerson.getPhoto());
                    }
            perPersonService.updatePerPerson(perPerson);
                }
            }
        } catch (Exception e) {
            throw new ServiceException("摄像头更新失败: " + e.getMessage());
        }

        // 4. 更新客户库
        ryCustomer.setUpdateTime(DateUtils.getNowDate());
        int customerResult = ryCustomerMapper.updateRyCustomer(ryCustomer);

        // 5. 同步更新人员管理表
        if (customerResult > 0) {
            try {
            PerPerson existingPerson = perPersonService.selectPerPersonByPid(original.getPid());
            if (existingPerson != null) {
                    // 将客户信息同步到已存在的人员记录
                    PerPerson updatePerson = convertToPerPerson(ryCustomer);
                    updatePerson.setId(existingPerson.getId());
                    updatePerson.setPid(original.getPid());
                    updatePerson.setUpdateBy(SecurityUtils.getUsername());
                    updatePerson.setUpdateTime(new Date());
                    
                    // 复制照片 - 使用最新的路径
                    updatePerson.setPhoto(ryCustomer.getFacePhoto());
                    
                    // 设置部门为客户类型
                    String department = "客户";
                    if (ryCustomer.getVipLevel() != null) {
                        switch (ryCustomer.getVipLevel()) {
                            case 1:
                                department = "普通客户";
                                break;
                            case 2:
                                department = "VIP客户";
                                break;
                            case 3:
                                department = "VVIP客户";
                                break;
                            default:
                                department = "客户";
                        }
                    }
                    updatePerson.setDepartment(department);
                    
                    log.info("同步更新客户到人员表, PID: {}", original.getPid());
                    perPersonService.updatePerPerson(updatePerson);
            } else {
                    log.info("人员表中不存在PID={} 的记录，创建新人员记录", original.getPid());
                    // 创建新的人员记录
                    PerPerson newPerson = convertToPerPerson(ryCustomer);
                    newPerson.setPid(original.getPid());
                    newPerson.setCreateBy(SecurityUtils.getUsername());
                    newPerson.setCreateTime(new Date());
                    newPerson.setDelFlag(0);
                    newPerson.setPhoto(ryCustomer.getFacePhoto());
                    
                    // 设置部门为客户类型
                    String department = "客户";
                    if (ryCustomer.getVipLevel() != null) {
                        switch (ryCustomer.getVipLevel()) {
                            case 1:
                                department = "普通客户";
                                break;
                            case 2:
                                department = "VIP客户";
                                break;
                            case 3:
                                department = "VVIP客户";
                                break;
                            default:
                                department = "客户";
                        }
                    }
                    newPerson.setDepartment(department);
                    
                    perPersonService.insertPerPerson(newPerson);
                }
            } catch (Exception e) {
                log.error("同步更新客户到人员表失败: {}", e.getMessage());
                // 不影响主流程，只记录日志
            }
        }

        return customerResult;
    }

    /**
     * 批量删除核心人员信息
     *
     * @param ids 需要删除的核心人员信息主键
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteRyCustomerByIds(Long[] ids) {
        int count = 0;
        for (Long id : ids) {
            count += deleteRyCustomerById(id);
        }
        return count;
    }

    /**
     * 删除核心人员信息
     *
     * @param id 核心人员信息主键
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteRyCustomerById(Long id) {
        RyCustomer customer = ryCustomerMapper.selectRyCustomerById(id);
        if (customer == null) {
            return 0;
        }

        String pid = customer.getPid();
        if (pid != null && !pid.isEmpty()) {
            try {
                // 获取此顾客关联的所有设备
                List<String> deviceSns = personDeviceRelService.getDeviceSnsByPersonPid(pid);
                
                // 查询人员ID
                PerPerson existingPerson = perPersonService.selectPerPersonByPid(pid);
                if (existingPerson != null) {
                    // 使用人员服务的删除方法，它会处理多设备关系的删除
                    perPersonService.deletePerPersonById(existingPerson.getId());
                } else {
                    // 如果找不到对应的人员记录，仅删除关联关系
                    personDeviceRelService.deleteAllRelationsByPersonPid(pid);
                }
            } catch (Exception e) {
                log.error("删除顾客关联关系失败: {}", e.getMessage());
            }
        }

        // 逻辑删除客户记录
        return ryCustomerMapper.updateDelFlagById(id, 1);
    }

    /**
     * 根据姓名和电话号码，查询用户信息，并绑定微信号
     * 
     * @param customer 包含姓名、电话号码和openid的客户信息
     * @return 受影响的行数
     */
    @Override
    public int updateRyCustomerConnectOpenid(RyCustomer customer) {
        return ryCustomerMapper.updateOpenidById(customer);
    }

    /**
     * 将RyCustomer对象转换为PerPerson对象
     * 
     * @param customer 顾客信息
     * @return 人员信息
     */
    private PerPerson convertToPerPerson(RyCustomer customer) {
        PerPerson person = new PerPerson();
        
        // 设置基本信息
        person.setPid(customer.getPid());
        person.setName(customer.getName());
        person.setCategory(customer.getCategory());
        person.setGender(customer.getGender());
        person.setAge(customer.getAge());
        person.setPhone(customer.getPhone());
        person.setIdCardNo(customer.getIdCardNo());
        person.setPhoto(customer.getFacePhoto());
        
        // 设置设备信息
        if (customer.getDeviceIds() != null && !customer.getDeviceIds().isEmpty()) {
            person.setDeviceIds(customer.getDeviceIds());
            person.setDeviceId(customer.getDeviceIds().get(0)); // 主设备ID
        } else if (customer.getDeviceSn() != null && !customer.getDeviceSn().isEmpty()) {
            person.setDeviceId(customer.getDeviceSn());
        }
        
        return person;
    }
    
    /**
     * 在照片路径中添加设备SN信息
     * 将原始路径修改为包含设备SN的格式
     */
    private String addDeviceSnToPhotoPath(String originalPath, String deviceSn) {
        if (originalPath == null || originalPath.isEmpty()) {
            return originalPath;
        }
        
        // 检查路径是否已经包含设备SN信息
        if (originalPath.contains("/device/" + deviceSn + "/")) {
            return originalPath; // 已经包含设备信息，不需要修改
        }
        
        // 假设原始路径格式为 /images/xxx.jpg
        if (originalPath.startsWith("/")) {
            return "/device/" + deviceSn + originalPath;
        } else {
            return "/device/" + deviceSn + "/" + originalPath;
        }
    }
    
    /**
     * 将相对路径转换为完整URL
     */
    public String convertToFullUrl(String relativePath) {
        if (relativePath == null || relativePath.isEmpty()) {
            log.debug("图片路径为空，返回原路径");
            return relativePath;
        }

        // 如果已经是完整的URL，直接返回
        if (relativePath.startsWith("http")) {
            log.debug("图片已是完整URL，无需转换: {}", relativePath);
            return relativePath;
        }

        String deviceSn = null;
        String actualPath = relativePath;

        // 检查是否是新格式的路径（包含设备SN）
        // 例如：/device/PFM1254O1009701/data/facelib/8178561152496049588.jpg
        java.util.regex.Pattern pattern = java.util.regex.Pattern.compile("/device/([^/]+)/(.+)");
        java.util.regex.Matcher matcher = pattern.matcher(relativePath);
        
        if (matcher.find()) {
            deviceSn = matcher.group(1);
            actualPath = matcher.group(2);
            log.debug("从路径中提取设备SN: {}, 实际路径: {}", deviceSn, actualPath);
        } else {
            log.debug("路径是旧格式，没有设备SN: {}", relativePath);
        }

        // 如果提取到设备SN，则使用设备的IP构建URL
        if (deviceSn != null && !deviceSn.isEmpty()) {
            DevDevice device = devDeviceService.selectDevDeviceBySn(deviceSn);
            
            if (device != null && device.getIp() != null && !device.getIp().isEmpty()) {
                // 构建基于设备IP的URL
                String ipPrefix = "http://" + device.getIp() + "/";
                String fullUrl;
                
                // 处理路径格式
                if (actualPath.startsWith("/")) {
                    fullUrl = ipPrefix + actualPath.substring(1);
                } else {
                    fullUrl = ipPrefix + actualPath;
                }
                
                log.debug("使用设备IP构建URL: {} -> {}", device.getIp(), fullUrl);
                return fullUrl;
            } else {
                log.warn("设备(SN:{})不存在或IP为空，使用配置的默认URL", deviceSn);
            }
        }
        
        // 对于旧格式或未能找到设备信息的情况，使用配置文件中的默认URL
        String prefix = cameraServerProperties.getPhotoPrefix();
        String fullUrl;
        
        // 处理路径格式
        if (prefix.endsWith("/") && actualPath.startsWith("/")) {
            fullUrl = prefix + actualPath.substring(1);
        } else if (!prefix.endsWith("/") && !actualPath.startsWith("/")) {
            fullUrl = prefix + "/" + actualPath;
        } else {
            fullUrl = prefix + actualPath;
        }
        
        log.debug("使用配置的默认URL前缀: {} -> {}", prefix, fullUrl);
        return fullUrl;
    }
}
